/**
 * 
 */
package com.zznode.client.wlanpolling.model;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

/**
 * @author Jerome
 *
 */
public abstract class GeneralInfo {
	
	public final String TAG = getClass().getSimpleName();
	
	private Map<String, Boolean> modified = new HashMap<String, Boolean>();
	
	public abstract String getGroupName();
	public abstract int getLayoutID();
	public abstract void bind(View root);
	public abstract int getRootID();
	
	public boolean isModified(String name){
		Boolean b = modified.get(name);
		if(b == null){
			return false;
		} else {
			return b;
		}
	}
	
	public void modified(String name){
		modified.put(name, true);
	}
	
	protected void addTextChangeListener(final EditText et, final String fieldName){
		boolean isModified = isModified(fieldName);
		if(isModified){
			et.setTextColor(Color.RED);
		}
		Field _field = null;
		try {
			_field = getClass().getField(fieldName);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
		if(_field != null){
			final Field field = _field;
			et.addTextChangedListener(new TextWatcher(){

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onTextChanged(CharSequence s, int start, int before,
						int count) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void afterTextChanged(Editable s) {
					try {
						String newValue = s.toString();
						final String oldValue = (String)field.get(GeneralInfo.this);
						if(newValue != null && !"".equals(newValue) && oldValue != null && !newValue.equals(oldValue)){
							field.set(GeneralInfo.this, s.toString());
							et.setTextColor(Color.RED);
							modified.put(fieldName, true);
						}						
					} catch (Exception e) {
						Log.e(TAG, e.getMessage());
					}
				}
				
			});
		}
	}
}
